'use strict'

import { app, protocol, BrowserWindow, ipcMain, dialog } from 'electron'
// 引入 store
import './store'
import sqlServer from './sqlServer'
// 主业务窗口、登录窗口
import mainWindow from './windows/mainWindow'
import loginWindow from './windows/loginWindow'

// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production';

// 初始化本地数据库连接
(async function () {
  global.sequelize = await sqlServer.init()
})()

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

const { createWindow: createMainWin, getWindow: getMainWindow } = mainWindow
const { createWindow: createLoginWin, getWindow: getLoginWindow } = loginWindow

// 创建登录窗口
async function createWindow () {
  createLoginWin()
}

// 登录事件
ipcMain.on('login', function (event, msg) {
  const loginWin = getLoginWindow()
  if (loginWin) loginWin.hide()

  const mainWin = getMainWindow()
  if (mainWin) {
    mainWin.show()
  } else {
    createMainWin()
  }
})

// 退出所有窗口触发
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 激活app
app.on('activate', () => {
  const loginWin = getLoginWindow()
  const mainWin = getMainWindow()

  if (loginWin) {
    if (!loginWin.isVisible()) {
      if (mainWin) {
        if (!mainWin.isVisible()) {
          mainWin.show() // 只显示窗口，不重复启动
        }
      } else {
        loginWin.show()
      }
    }
  }

  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      // await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
